package gin

import (
	"fmt"
	"mime"
	"net/http"

	"github.com/gin-contrib/static"
	"github.com/gin-gonic/gin"
	Log "github.com/cihub/seelog"
	. "gitee.com/tomatomeatman/golang-repository/bricks/model"
)

type GinUtil struct{}

// 请求类型枚举
type RequestType string

const (
	GET     RequestType = "GET"
	POST    RequestType = "POST"
	DELETE  RequestType = "DELETE"
	PUT     RequestType = "PUT"
	OPTIONS RequestType = "OPTIONS"
)

var (
	httpHandleFunc = make(map[string]HttpHandleInfo) //http控制层接口信息集合
)

// http控制层接口信息
type HttpHandleInfo struct {
	Url  string
	Type RequestType
	Fun  func(ctx *gin.Context) interface{}
}

//设置跨域
func (this GinUtil) SetCors(r *gin.Engine) {
	r.Use(this.Cors())
}

//跨域函数
func (this GinUtil) Cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method
		origin := c.Request.Header.Get("Origin")
		if origin != "" {
			c.Header("Access-Control-Allow-Origin", "*") // 可将将 * 替换为指定的域名
			c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
			//c.Header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization")
			//c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Cache-Control, Content-Language, Content-Type")
			c.Header("Access-Control-Allow-Headers", "*")
			c.Header("Access-Control-Expose-Headers", "*")
			c.Header("Access-Control-Allow-Credentials", "true")
		}
		if method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
		}
		c.Next()
	}
}

//设置静态路径
func (this GinUtil) SetStatic(r *gin.Engine, webroot string) {
	_ = mime.AddExtensionType(".js", "application/javascript") // 特殊处理JS文件的Content-Type
	r.Use(static.Serve("/", static.LocalFile(webroot, true)))  // 前端项目静态资源
}

// 注册web接口
func (this GinUtil) RegisterController(url string, iType RequestType, handler func(ctx *gin.Context) interface{}) {
	_, ok := httpHandleFunc[url]
	if ok {
		Log.Error("链接重复:" + url)
		return
	}

	httpHandleFunc[url] = HttpHandleInfo{
		Url:  url,
		Type: iType,
		Fun:  handler,
	}
}

// 取注册的web接口
func (this GinUtil) GetController() map[string]HttpHandleInfo {
	return httpHandleFunc
}

// 取注册的web接口
func (this GinUtil) GetHandleFunc(urlKey string, InterceptorFunc func(ctx *gin.Context) bool,
	controllerMap map[string]HttpHandleInfo) func(ctx *gin.Context) {
	result := func(ctx *gin.Context) {
		urlStr := ctx.Request.URL.Path

		if nil != InterceptorFunc {
			if !InterceptorFunc(ctx) {
				return
			}
		}

		httpHandleInfo := controllerMap[urlKey] //给个默认
		vb := false
		for runKey := range controllerMap {
			if runKey != urlStr {
				continue
			}

			httpHandleInfo = controllerMap[runKey]
			vb = true
			break
		}

		if !vb {
			return
		}

		obj := httpHandleInfo.Fun(ctx)
		switch obj.(type) {
		case *MsgEmity, MsgEmity:
			ctx.JSONP(http.StatusOK, obj)
			break
		default:
			ctx.Writer.Write([]byte(fmt.Sprintf("%v", obj)))
		}
	}

	return result
}
